<?php

namespace App\Http\Controllers;

use App\Models\BindingRecord;
use App\Models\ChatRecords;
use App\Models\FriendList;
use App\Models\User;
use App\Models\UserChatGroup;
use App\Models\UserChatGroupUser;
use GatewayClient\Gateway;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Builder;

/**
 * 客户端聊天控制器
 * Class ChatController
 * @package App\Http\Controllers
 */
class ChatController extends BaseController
{
    //前端(用户端)加载试图 1v1聊天
    public function index(Request $request)
    {
        $user_id = $request->input('user_id', null);//客户端用户id(都是用户表的id,这个id是不能通信的,通信时双方必须都使用绑定表中的id)
        $friend_id = $request->input('friend_id',null);//好友的id(都是用户表的id,这个id是不能通信的,通信时双方必须都使用绑定表中的id)
        return view('web.chat.index', compact('user_id','friend_id'));
    }

    //前端(用户端)加载群组连天试图 群聊天
    public function groupIndex(Request $request)
    {
        $user_id = $request->input('user_id', null);//客户端用户id(都是用户表的id,这个id是不能通信的,通信时双方必须都使用绑定表中的id)
        $group_id = $request->input('group_id',null);//群组的id(user_chat_groups表的id,这个id是不能通信的)

        //清除当前用户在这个群组中的未读消息数量记录
        UserChatGroupUser::where('chat_group_id',$group_id)
            ->where('user_id',$user_id)
            ->update(['unread_num'=>0]);

        $user_nickname =User::where('id',$user_id)->value('nickname');

        return view('web.chat.group_index', compact('user_id','group_id','user_nickname'));
    }

    //绑定用户id与workmain_id
    public function binding(Request $request)
    {
        $user_id = $request->input('user_id');//数据库中用户真实id
        $friend_id = $request->input('friend_id', 0);//收件人id
        $role = $request->input('role','2');//当前登录用户身份|1:客服,2:用户
        $client_id = $request->input('client_id');//workmain的临时id标识

        $addressee_name = '';
        $addressee_id = '';
        if ($friend_id){
            $binding = BindingRecord::where([
                ['user_id', $friend_id],
                ['role', $role],//1:客服,2:用户
            ])->first();
            $addressee_id = $binding['id'] ?? '';
            $addressee_name = User::where('id',$friend_id)->value('nickname');
            if (!$binding){
                $addressee_name = "{$addressee_name}(离线)";
            }
        }

        //绑定信息存在则更新/入库
        $res = [
            'msg' => '绑定成功',
            'type' => 'binding_success',
            'bind_id' => 0,//绑定表id
            'addressee_id' => $addressee_id,//绑定表id
            'addressee_name' => $addressee_name,
        ];

        //换取全局通用bind_id
        $binding = BindingRecord::where([
            ['user_id', $user_id],
            ['role', $role],//1:客服,2:用户
        ])->first();
        if ($binding) {
            //更新绑定信息
            $binding->update(['client_id' => $client_id]);
            $res['bind_id'] = $binding['id'];
        } else {
            //创建绑定关系
            $date = date('Y-m-d H:i:s');
            $bind_id = BindingRecord::insertGetId([
                'created_at' => $date,
                'user_id' => $user_id,
                'role' => $role,
                'client_id' => $client_id,
            ]);
            $res['bind_id'] = $bind_id;//绑定后的id,此id为我们IM只平台中用户与用户件通信标识身份的唯一id
        }

        //开始绑定
        Gateway::bindUid($client_id, $res['bind_id']);

        return $this->send(200, 'success', $res);
    }

    //分配客服
    private function assignCustomerService()
    {
        //获取全部在线的客服
        $bind_id = BindingRecord::where('role', 1)->pluck('id');
        if (!count($bind_id)) {
            $this->send(500, '暂无在线客服');
        }
        $ol_bind_id = [];
        Gateway::$registerAddress = '127.0.0.1:' . config('gateway_worker.register_port');
        foreach ($bind_id as $v) {
            $res = Gateway::isUidOnline($v);//检查uid是否在线
            if ($res) {
                $ol_bind_id[] = $v;
            }
        }
        //随机选中一个客服id与当前用户成为好友关系
        if ($ol_bind_id){
            $service_id = $ol_bind_id[array_rand($ol_bind_id)];
        }else{
            //没有客服在线
            $service_id = 1;//默认客服id
        }
        //返回选中的客服id

        return $service_id;
    }

    /**
     * 创建好友关系
     * @param int $waiter_bind_id 客服bind_id
     * @param int $client_bind_id 用户bing_in
     */
    private function createFriendships(int $waiter_bind_id, int $client_bind_id)
    {
        $friend = FriendList::where([
            ['waiter_bind_id', $waiter_bind_id],
            ['client_bind_id', $client_bind_id],
        ])->first();
        if (!$friend) {
            FriendList::create([
                'waiter_bind_id' => $waiter_bind_id,
                'client_bind_id' => $client_bind_id,
            ]);
        }
    }

    /**
     * 发送消息
     * @param Request $request
     */
    public function sendMassage(Request $request)
    {
        $message = [
            'user_id'=>$request->input('user_id'),
            'friend_id'=>$request->input('friend_id'),
            'bind_id' => $request->input('bind_id'),//当前用户id(binding_records表id)
            'role' => $request->input('role','2'),//用户身份,1:客服,2:用户
            'addressee_id' => $request->input('addressee_id'),//收件人id(binding_records表id)
            'type' => $request->input('type'),//消息类型
            'content' => $request->input('content'),//消息内容
        ];
        if (!$message['bind_id'] || !$message['addressee_id'] || !$message['type'] || !$message['content']) {
            return $this->send(500, '发送失败');
        }

        if (!in_array($message['type'], ['text', 'images', 'link','file'])) {
            return $this->send(403, '消息类型不合法');
        }

        $is_read = 2;//是否已读|默认为1:否,2:是
        if ($message['role'] == 2) {
            //通过缓存得到当前的好友是否正在和当前客户聊天
            $service_user_id = Cache::get('customer_service_id_' . $message['addressee_id']);
            //如果可和正在和当前客户聊天就把消息状态变为已读
            if ($service_user_id == $message['bind_id']) {
                $is_read = 1;
            }
        }
        $content = json_encode($message,JSON_UNESCAPED_UNICODE);
        //将消息存入数据库
        ChatRecords::create([
            'sender_id' => $message['bind_id'],//发件人id|(数据来自binding_records表)
            'addressee_id' => $message['addressee_id'],//收件人id|(数据来自binding_records表)
            'content' => $message,//发送的内容json格式
            'message_type' => $message['type'],//消息类型|text:文本(字符串),images:图片(json格式),link:链接(json格式),file:文件类型(json格式)
            'chat_type'=>'user',//聊天类型|user=1v1聊天,group=群聊
            'is_read' => $is_read,//是否已读|默认为1:否,2:是
        ]);

        Gateway::$registerAddress = '127.0.0.1:' . config('gateway_worker.register_port');
        Gateway::sendToUid($message['addressee_id'], $content);//给发件人的uid网站页面发送数据
        $res = [
            'bind_id'=>$message['bind_id'],
            'addressee_id'=>$message['addressee_id'],
        ];
        $this->send(200, 'success',$res);
    }

    //加入群组
    public function joinGroup(Request $request){
        $bind_id = $request->input('bind_id');//当前用户id(binding_records表id)
        $user_id = $request->input('user_id');//当前用户id(user表id)
        $client_id = BindingRecord::where('id',$bind_id)->value('client_id');
        $user_chat_groups_id = $request->input('group_id');//用户聊天群组id|user_chat_groups.id
        $data = UserChatGroup::where('id',$user_chat_groups_id)->first();
        $res = [
            'code'=>200,
            'msg' => '绑定成功',
            'type' => 'join_group',
            'group_id' => $data['id'],
            'group_name' => $data['name']
        ];


        try {
            $group = UserChatGroupUser::where('user_id',$user_id)
                ->where('chat_group_id',$user_chat_groups_id)
                ->first();
            if (!$group){
                UserChatGroupUser::create([
                    'chat_group_id'=>$user_chat_groups_id,
                    'user_id'=>$user_id,
                ]);
            }

            Gateway::$registerAddress = '127.0.0.1:' . config('gateway_worker.register_port');
            Gateway::joinGroup($client_id, $user_chat_groups_id);
        } catch (\Exception $e) {
            $res['code'] = 500;
            $res['msg'] = $e->getMessage();
        }
        return $res;
    }

    //发送群组消息
    public function sendToGroupMassage(Request $request){
        $group_id = $request->input('group_id');//用户聊天群组id|user_chat_groups.id
        $user_id = $request->input('user_id');//当前用户的user.id
        $message = [
            'bind_id' => $request->input('bind_id'),//当前用户id(binding_records表id)
            'role' => $request->input('role','2'),//用户身份,1:客服,2:用户
            'group_id' => $group_id,//群id
            'type' => $request->input('type'),//消息类型
            'content' => $request->input('content'),//消息内容
        ];

        ChatRecords::create([
            'sender_id' => $message['bind_id'],//发件人id|(数据来自binding_records表)
            'group_id' => $message['group_id'],//聊天群组id|user_chat_groups.id(和收件人id字段二选一填)
            'content' => $message,//发送的内容json格式
            'message_type' => $message['type'],//消息类型|text:文本(字符串),images:图片(json格式),link:链接(json格式),file:文件(如:.zpi,.text后缀之类的)
            'chat_type'=>'group',//聊天类型|user=1v1聊天,group=群聊
            'is_read' => 2,//是否已读|默认为1:否,2:是
        ]);
        $message['user_name'] = User::where('id',$user_id)->value('nickname');//发信任的昵称
        $content = json_encode($message,JSON_UNESCAPED_UNICODE);


        //当然用户是否被禁言
        $is_mute = UserChatGroupUser::where('chat_group_id', $group_id)
            ->where('user_id', $user_id)
            ->value('is_mute');

        if ($is_mute == 1){
            $this->send(500, '当前用户已被禁言');
        }


        //给这个群组中除自己外的全部用户的未读消息数量自增1
       UserChatGroupUser::where('chat_group_id',$group_id)
            ->Where('user_id','!=',$user_id)
            ->increment('unread_num');


        Gateway::$registerAddress = '127.0.0.1:' . config('gateway_worker.register_port');
        Gateway::sendToGroup($group_id, $content);
        $res = [
            'bind_id'=>$message['bind_id'],
            'group_id'=>$message['group_id'],
        ];
        $this->send(200, 'success',$res);
    }

    //获取群组聊天记录列表
    public function getGroupMsgList(Request $request){
        $page = $request->input('page', 1);
        $finally_msg_id = $request->input('msg_max_id', '');//当前聊天记录中的最大的聊天记看id
        $limit = $request->input('limit', 100);
        $offset = ($page - 1) * $limit;

        $group_id = $request->input('group_id');//用户聊天群组id|user_chat_groups.id
        $user_id = $request->input('user_id');//当前用户的user.id
        $sender_id = $request->input('sender_id');//发件人id|(数据来自binding_records表id)

        //获取群组聊天记录
        $data = ChatRecords::where('group_id',$group_id);
        if (!empty($finally_msg_id)){
            $data = $data->where('id','<',$finally_msg_id);
        }
        $data = $data->with([
            'binding_record'=>function($query){
                $query->with(['user'=>function($query){
                    $query->select(['id','username','nickname']);
                }]);
            }
        ])
            ->offset($offset)
            ->limit($limit)
            ->orderBy('id','desc')
            ->get();

        if (count($data)){
            $data  = $data->toArray();
            usort($data, function($a, $b) {
                return $a['id'] <=> $b['id'];
            });

            foreach($data as &$v){
                $v['created_at'] =  $this->tranTime(strtotime($v['created_at']));
            }

            return $this->send(200, 'success',$data);
        }

        return $this->send(200, 'success',[]);



    }

    //清空指定用户在指定群组中的未读消息数量
    public function delUnreadNum(Request $request){
        $user_id = $request->input('user_id', null);//客户端用户id(都是用户表的id,这个id是不能通信的,通信时双方必须都使用绑定表中的id)
        $group_id = $request->input('group_id',null);//群组的id(user_chat_groups表的id,这个id是不能通信的)
        if (!$user_id || !$group_id){
            return $this->send(500, 'error');
        }

        //清除当前用户在这个群组中的未读消息数量记录
        $res = UserChatGroupUser::where('chat_group_id',$group_id)
            ->where('user_id',$user_id)
            ->update(['unread_num'=>0]);

        $this->send(200, 'success',$res);
    }

}
